import { Stepper } from 'antd-mobile'
import React, { useEffect, useState, useRef } from 'react'
import { cart_list, remove, removeall, selectall, selectone, updatenum } from '../../apis/shopcart'
import Navbar from '../../components/Navbar'
import "../../style/shopcart.scss"
import { Checkbox, Button, SwipeAction, Dialog, Empty } from 'antd-mobile'
import { SwipeActionRef } from 'antd-mobile/es/components/swipe-action'
import Love from '../../components/Love'
import { useNavigate } from 'react-router-dom'
import { addorder, deleteCartItem } from '../../apis/order'
export default function Shopcart() {
  const [data, setdata] = useState([])
  const [checkedarr, setcheckedarr] = useState([])
  const [num, setnum] = useState(0)
  const [price, setprice] = useState(0)
  const [bool, setbool] = useState(true)
  const ref = useRef<SwipeActionRef>(null)
  const navigate = useNavigate()
  useEffect(() => {
    list()
    if (localStorage.getItem("userid") == null) {
      navigate("/login")
    }
  }, [])
  useEffect(() => {

    isChecked()
    if (data && data.length !== 0) total()
  }, [data])

  let list = async () => {
    let res = await cart_list(localStorage.getItem("userid"))
    setdata(res.data)
    // console.log(res);
  }

  let change = async (cartid: String, flag: boolean) => {
    flag = !flag
    await selectone(cartid, flag)
    list()
  }

  let isChecked = () => {
    if (data) {
      let arr = data.filter((item: any) => {
        return item.flag
      })
      setcheckedarr(arr)
    }
  }

  let total = () => {
    let price = 0;
    let num = 0
    let total_arr = data.map((item: any) => {
      if (item.flag) {
        price += item.num * item.originprice
        num += item.num
      }
      return [price, num]
    })
    setprice(total_arr[total_arr.length - 1][0])
    setnum(total_arr[total_arr.length - 1][1])
  }

  let del = () => {
    if (checkedarr.length === data.length) {
      removeall(localStorage.getItem("userid"))
    } else {
      checkedarr.forEach((item: any) => {
        remove(item.cartid)
      })
    }
    console.log();

  }

  let order = async () => {
    let res: any = await addorder(localStorage.getItem("userid"))
    navigate("/OrderConfirm", { state: { time: res.time } });
    console.log(res);
    let ok = await deleteCartItem(localStorage.getItem("userid"))
  }
  return (
    <div className='shopcart'>
      <Navbar right={<p onClick={() => setbool(!bool)}>管理</p>} title="购物车" />
      {
        data ?
          <>
            <div className="list">
              <Checkbox.Group value={checkedarr}>
                {

                  data &&
                  data.map((item: any) => {
                    return (
                      <SwipeAction
                        key={item.cartid}
                        ref={ref}
                        closeOnAction={false}
                        rightActions={[
                          {
                            key: 'delete',
                            text: '删除',
                            color: 'danger',
                            onClick: async () => {
                              const result = await Dialog.confirm({
                                content: '确定要删除吗？',
                              })
                              if (result) {
                                remove(item.cartid)

                              } else {
                                ref.current?.close()
                              }
                            },
                          },
                        ]}
                      >
                        <div className="item">
                          <Checkbox checked={item.flag} onChange={() => { change(item.cartid, item.flag) }}></Checkbox>
                          <img src={item.img1} alt="" />
                          <div className="info">
                            <div className="name">{item.proname}</div>

                            <div className="price">
                              <p>￥<span>{item.originprice}</span></p>

                              <Stepper min={1} digits={0} defaultValue={item.num} onChange={(v) => { updatenum(item.cartid, v); list() }}
                              />

                            </div>
                          </div>
                        </div>
                      </SwipeAction>
                    )
                  })
                }
              </Checkbox.Group>
            </div>

            <Love />

            <div className="account">
              <Checkbox
                checked={data ? checkedarr.length === data.length : false}
                onChange={(v) => { selectall(localStorage.getItem("userid"), v); list() }}
              >
                全选
              </Checkbox>

              {
                bool ? <p>
                  合计:<span>￥<span> {price}</span></span>
                  <Button color='danger' shape='rounded' onClick={() => { order() }}>去结算({num})</Button>
                </p>
                  :
                  <Button color='danger' shape='rounded' onClick={() => { del() }}>删除</Button>
              }
            </div>
          </>
          :
          <>
            <Empty
              style={{ padding: '64px 0' }}
              imageStyle={{ width: 128 }}
              description='暂无数据'
            />

            <Love />

          </>
      }
    </div>
  )
}
